// pages/region-bindings/region-bindings.ts
import { MerchantAPI } from '../../utils/api'
import { MerchantRegionBinding, Region } from '../../types/region'

interface RegionBindingDisplay extends MerchantRegionBinding {
  statusText: string;
}

Page({
  data: {
    loading: false,
    bindings: [] as RegionBindingDisplay[],
    regions: [] as Region[],
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    showAddModal: false,
    selectedRegionIndex: -1, // 选择的区域索引
    serviceRadius: '',
    bindingStatus: 1
  },

  onLoad() {
    this.loadBindings();
    this.loadRegions();
  },

  onPullDownRefresh() {
    this.setData({ pageNum: 1, hasMore: true });
    this.loadBindings(true);
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({ pageNum: this.data.pageNum + 1 });
      this.loadBindings();
    }
  },

  // 加载区域绑定列表
  async loadBindings(refresh: boolean = false) {
    if (this.data.loading) return;

    this.setData({ loading: true });

    try {
      const response = await MerchantAPI.getMerchantRegionBindingList({
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      });

      if (response && response.code === 200) {
        const bindings = response.rows || [];
        const totalCount = response.total || 0;

        const displayBindings: RegionBindingDisplay[] = bindings.map((binding: MerchantRegionBinding) => ({
          ...binding,
          statusText: binding.status === 1 ? '启用' : '禁用'
        }));

        this.setData({
          bindings: refresh ? displayBindings : [...this.data.bindings, ...displayBindings],
          hasMore: this.data.bindings.length + displayBindings.length < totalCount
        });
      }
    } catch (error: any) {
      console.error('加载区域绑定失败:', error);
      const errorMsg = error?.msg || '加载失败';
      if (error?.code === 403) {
        wx.showModal({
          title: '权限提示',
          content: '当前账号暂无区域绑定管理权限，请联系管理员在后台配置以下权限：\n\n• merchant:merchant_bindings:list\n• merchant:merchant_bindings:add\n• merchant:merchant_bindings:edit\n• merchant:merchant_bindings:remove',
          showCancel: false,
          confirmText: '我知道了'
        });
      } else {
        wx.showToast({ title: errorMsg, icon: 'none' });
      }
    } finally {
      this.setData({ loading: false });
      if (refresh) wx.stopPullDownRefresh();
    }
  },

  // 加载平台区域列表（用于选择器）
  async loadRegions() {
    // 注意：这里需要调用平台区域列表接口，但该接口需要特殊权限
    // 如果没有权限，可以考虑：
    // 1. 让后端提供一个不需要权限的区域查询接口
    // 2. 或者在创建绑定时由后端返回可用区域列表
    // 暂时先跳过权限检查，直接使用已绑定的区域作为数据源
    console.log('区域选择功能需要后端支持无权限的区域列表接口');
  },

  // 显示添加弹窗
  showAddBindingModal() {
    if (this.data.regions.length === 0) {
      wx.showToast({
        title: '请等待区域列表加载完成',
        icon: 'none'
      });
      return;
    }
    this.setData({
      showAddModal: true,
      selectedRegionIndex: -1,
      serviceRadius: '',
      bindingStatus: 1
    });
  },

  // 关闭弹窗
  closeAddModal() {
    this.setData({ showAddModal: false });
  },

  // 选择区域
  onRegionChange(e: any) {
    const index = parseInt(e.detail.value);
    this.setData({
      selectedRegionIndex: index
    });
  },

  // 输入服务半径
  onRadiusInput(e: any) {
    this.setData({
      serviceRadius: e.detail.value
    });
  },

  // 选择状态
  onStatusChange(e: any) {
    this.setData({
      bindingStatus: parseInt(e.detail.value)
    });
  },

  // 添加区域绑定
  async addBinding() {
    const { selectedRegionIndex, regions, serviceRadius, bindingStatus } = this.data;

    if (selectedRegionIndex < 0 || !regions[selectedRegionIndex]) {
      wx.showToast({ title: '请选择区域', icon: 'none' });
      return;
    }

    const selectedRegion = regions[selectedRegionIndex];

    try {
      wx.showLoading({ title: '添加中...' });

      const response = await MerchantAPI.createRegionBinding({
        regionId: selectedRegion.regionId,
        serviceRadius: serviceRadius || '5',
        status: bindingStatus
      });

      if (response && response.code === 200) {
        wx.showToast({ title: '添加成功', icon: 'success' });
        this.closeAddModal();
        this.setData({ pageNum: 1 });
        this.loadBindings(true);
      } else {
        wx.showToast({ title: response.msg || '添加失败', icon: 'none' });
      }
    } catch (error) {
      console.error('添加区域绑定失败:', error);
      wx.showToast({ title: '添加失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },

  // 切换绑定状态
  async toggleBindingStatus(e: any) {
    const binding: RegionBindingDisplay = e.currentTarget.dataset.binding;
    const newStatus = binding.status === 1 ? 0 : 1;

    wx.showModal({
      title: '确认操作',
      content: `确定要${newStatus === 1 ? '启用' : '禁用'}该区域绑定吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '处理中...' });

            const response = await MerchantAPI.updateRegionBinding({
              bindingId: binding.bindingId,
              regionId: binding.regionId,
              serviceRadius: binding.serviceRadius,
              status: newStatus
            });

            if (response && response.code === 200) {
              wx.showToast({ title: `${newStatus === 1 ? '启用' : '禁用'}成功`, icon: 'success' });
              this.setData({ pageNum: 1 });
              this.loadBindings(true);
            } else {
              wx.showToast({ title: response.msg || '操作失败', icon: 'none' });
            }
          } catch (error) {
            console.error('切换状态失败:', error);
            wx.showToast({ title: '操作失败', icon: 'none' });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },

  // 删除区域绑定
  deleteBinding(e: any) {
    const binding: RegionBindingDisplay = e.currentTarget.dataset.binding;

    wx.showModal({
      title: '确认删除',
      content: '删除后将无法恢复，确定要删除该区域绑定吗？',
      confirmColor: '#ff4444',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '删除中...' });

            const response = await MerchantAPI.deleteRegionBinding([binding.bindingId!]);

            if (response && response.code === 200) {
              wx.showToast({ title: '删除成功', icon: 'success' });
              this.setData({ pageNum: 1 });
              this.loadBindings(true);
            } else {
              wx.showToast({ title: response.msg || '删除失败', icon: 'none' });
            }
          } catch (error) {
            console.error('删除区域绑定失败:', error);
            wx.showToast({ title: '删除失败', icon: 'none' });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  }
});
